"nodejs ui";
import fs from "fs";
import {
    exec,
    createShell
} from 'shell';
import {
    Deferred
} from "lang";
import $ui from "ui";

(await import ("rhino")).install();

const Intent = android.content.Intent;
const getUrl = new Deferred();


class LogActivity extends $ui.Activity {
    get initialStatusBar() {
        return {
            color: '#ffffff',
            light: true
        }
    }

    get layoutXml() {
        return `
<vertical>
    <progressbar id="progressbar" indeterminate="true" style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"/>
    <globalconsole id="console" w="*" h="*"/>
</vertical>
`
    }

    onCreate(savedInstanceState) {
        super.onCreate(savedInstanceState);
        getUrl.promise().then(() => this.finish());
    }
}

$ui.startActivity(LogActivity, {
    flags: Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_MULTIPLE_TASK | Intent.FLAG_ACTIVITY_NEW_TASK,
});
$ui.activityLifecycle.on('all_activities_destroyed', () => {
    process.exit();
});


const sh = await createShell();
sh.on('line', (line) => {
    console.log(line);
});

if (!fs.existsSync('./node_modules')) {
    console.info('安装npm依赖中，请保持网络通畅，可能需要几分钟或者更长，若失败请手动在命令行安装');
    await sh.exec('npm i --no-bin-links');
}
console.log("开始编译。");
const r = await sh.exec('npm test');
if (r.code != 0) {
    console.error(r.stdout);
    console.log("编译失败！");
} else {
    console.log("编译成功。");
    await import ("./dist/main.node.js");
    getUrl.resolve();
}